import { createRouter, createWebHashHistory, RouterView } from 'vue-router'
import {h} from 'vue'
const Layout = () => { return import('@/views/Layout.vue') }
const Home = () => { return import('@/views/home') }
const TopCategory = () => { return import('@/views/category/index') }
const SubCategory = () => { return import('@/views/category/sub-category') }
const Goods = () => { return import('@/views/goods/index.vue') }
const Login = () => { return import('@/views/login/index') }
const Cart = () => { return import('@/views/cart/index') }
const LoginCallback = () => { return import("@/views/login/callback") }
const checkout = () => { return import("@/views/member/pay/checkout") }
const PayIndex = () => import('@/views/member/pay/index')
const callback = () => import('@/views/member/pay/components/result')
const MemberLayout = () => import('@/views/member/Layout')
const MemberHome = () => import('@/views/member/home')
const MemberOrder = () => import('@/views/member/order')
const MemberOrderDetail = () => import('@/views/member/order/order-detail')
//路由规则
const routes = [{
    path: '',
    redirect:'',
    component: Layout,
    children: [
        { path: '', component: Home },
        { path: 'category/:id', component: TopCategory },
        { path: 'category/sub/:id', component: SubCategory },
        { path: 'product/:id', component: Goods },
        { path: 'cart', component: Cart },
        { path: 'member/checkout', component: checkout },
        { path: 'member/pay', component: PayIndex },
        { path: 'pay/callback', component: callback },
        {
            path: '/member', component: MemberLayout,
            children: [
                //三级路由
                { path: '', component: MemberHome },
                {
                    path: 'order', component:{render:() =>h(<RouterView/>)},
                    children:[
                        { path: '', component: MemberOrder },
                        { path: ':id', component: MemberOrderDetail }
                    ]
                }
            ]
        }
    ]
},
{
    path: '/login',
    component: Login
},
{
    path: '/login/callback',
    component: LoginCallback
}
]

//vue2.0 new vueRouter({}) 创建路由实例
//vue3.0 createRouter({})
const router = createRouter({
    //使用hash路由模式
    history: createWebHashHistory(),
    routes,
    scrollBehavior() {
        return { top: 0, left: 0 }
    }
})
import store from '@/store'
// 前置导航守卫

router.beforeEach((to, from, next) => {
    if (to.fullPath === '/login') {
        store.dispatch('user/setRedirectiveUrl', from.fullPath)
    }
    // 用户信息
    const { token } = store.state.user.profile
    // 跳转去member开头的地址却没有登录
    if (to.path.startsWith('/member') && !token) {
        store.dispatch('user/setRedirectiveUrl', from.fullPath)
        next({ path: '/login', query: { redirectUrl: to.fullPath } })
    }
    next()
})


export default router